import { Component, OnInit } from '@angular/core';
import {Message, TreeNode} from "primeng/api";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {EquipmentService} from "../equipment.service";

@Component({
  selector: 'app-equipment-class',
  templateUrl: './equipment-class.component.html',
  styleUrls: ['./equipment-class.component.css']
})
export class EquipmentClassComponent implements OnInit {
  totalRecords;
  equipmentModel =[];
  assetManDatas: TreeNode[];      // 资产管理树
  titleName: string;                 // 右边表格标题名
  tableDatas: any;                   // 表格数据
  val1: string;                      // 新增启用
  addDisplay: boolean;               // 新增模态框显示控制
  canAdd: boolean;                   // 是都可以新增
  dataName: string;                  // 新增名称字段
  msgs: Message[] = [];              // 表单验证提示
  nodeFather: string;                // 表格中选中的节点的父节点
  nodeDid: string;                   // 表格中选中的节点的did
  nodeDep: string;                   // 表格中选中的节点Dep
  addOrEdit: string;                 // 新增或者编辑按钮显示哪一个
  did: string;                       // 重新请求表格的需要的did
  dep: string;                       // 重新请求表格的需要的dep
  msgPop: Message[];                 // 操作请求后的提示
  selected: any;                     // 被选中的节点
  title: string;                     // 弹出框标题
  dialogDisplay: boolean;            // 删除框控制
  idsArray = [];                     // 数据
  isDisable: boolean;                // 显示设置
  myForm: FormGroup;

  constructor(
    private equipmentService: EquipmentService,
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.initForm();
    this.equipmentService.getAssetManTreeDatas().subscribe(res => {
      this.assetManDatas  = res;
    });
    this.val1 = '启用';
    this.addDisplay = false;
    this.canAdd = true;
    this.dialogDisplay = false;
    this.isDisable = false;
  }

  initForm() {
    this.myForm = this.fb.group({
      'nodeName': ['', Validators.required,Validators.maxLength(16)],
      'nodeActive': '',
      'nodeUnactive': ''
    });
  }
  get isDirty(): boolean {
    let valid = !this.myForm.controls['nodeName'].untouched && !this.myForm.controls['nodeName'].value;
    let validAgain = this.myForm.controls['nodeName'].untouched && !this.myForm.controls['nodeName'].value;
    // let result;
    // console.log('valid----->', valid);
    // console.log('validAgain----->', validAgain);
    return !( valid || validAgain);
  }
  // 组织树懒加载
  nodeExpand(event) {
    if (event.node) {
      this.equipmentService.getAssetManTreeDatas(event.node.did, event.node.dep).subscribe(res => {
        event.node.children  = res;
      });
    }
  }
  // 组织树选中
  NodeSelect(event) {
    // console.log(event);
    // console.log(parseInt(event.node.label));
    if (parseInt(event.node.dep) < 3) {
      this.titleName = event.node.label;
      this.nodeFather = event.node.did;
      this.nodeDep = event.node.dep;
      this.did = event.node.did;
      this.dep = event.node.dep;
      this.canAdd = false;
      this.equipmentService.getAssetManTreeDatas(event.node.did, event.node.dep).subscribe(res => {
        this.tableDatas = res;
        this.totalRecords = this.tableDatas.length;
        this.equipmentModel = this.tableDatas.slice(0, 10);
      });
    }
  }
  loadCarsLazy(event) {
    setTimeout(() => {
      if (this.tableDatas) {
        this.equipmentModel = this.tableDatas.slice(event.first, (event.first + event.rows));
      }
    }, 250);
  }


  add() {
    this.myForm.get('nodeName').enable({ onlySelf: true, emitEvent: true});
    this.addDisplay = true;
    this.addOrEdit = 'add';
    this.dataName = '';
    this.title = '新增';
  }
  cancelMask(bool){
      this.addDisplay = false;
      this.msgs =[];
  }
  ansureAddDialog() {
    if ( !this.dataName ) {
      this.msgs = [];
      this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }else {
      this.equipmentService.addConfig(this.dataName, this.val1, this.nodeFather, this.nodeDep).subscribe(res => {
        // console.log(res);
        if (res === '00000') {
          this.msgPop = [];
          this.msgPop.push({severity: 'success', summary: '消息提示', detail: '新增成功'});
          this.refreshDataTable();
        }else {
          this.msgPop = [];
          this.msgPop.push({severity: 'error', summary: '提示消息', detail: '新增失败' + '\n' + res });
        }
      });
      this.addDisplay = false;
    }
  }

  edit(data) {
    // console.log(data);
    this.myForm.get('nodeName').enable({ onlySelf: true, emitEvent: true});
    this.dataName = data.label;
    this.nodeDid = data.did;
    this.nodeDep = data.dep;
    this.addDisplay = true;
    this.addOrEdit = 'edit';
    this.val1 = data.status;
    this.title = '编辑';
  }

  ansureEditDialog() {
    if ( !this.dataName ) {
      this.msgs = [];
      this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单' });
    }else {
      this.equipmentService.editConfig(this.dataName, this.val1, this.nodeDid, this.nodeDep, this.nodeFather).subscribe(res => {
        // console.log(res);
        if (res === '00000') {
          this.msgPop = [];
          this.msgPop.push({severity: 'success', summary: '消息提示', detail: '编辑成功'});
          this.refreshDataTable();
        }else {
          this.msgPop = [];
          this.msgPop.push({severity: 'error', summary: '提示消息', detail: '编辑失败' + '\n' + res });
        }
      });
      this.addDisplay = false;
    }
  }

  refreshDataTable() {
    this.equipmentService.getAssetManTreeDatas(this.did, this.dep).subscribe(res => {
      this.tableDatas = res;
    });
  }

  frezzeOrActive(data) {
    // console.log(data);
    let status = '';
    (data.status === '启用') && ( status = '冻结');
    (data.status === '冻结') && ( status = '启用');
    this.equipmentService.editConfig(data.label, status, data.did, data.dep, data.father).subscribe(res => {
      if (res === '00000') {
        this.msgPop = [];
        this.msgPop.push({severity: 'success', summary: '消息提示', detail: status + '成功'});
        this.refreshDataTable();
      }else {
        this.msgPop = [];
        this.msgPop.push({severity: 'error', summary: '提示消息', detail: status + '失败' + '\n' + res });
      }
    });
  }
  delete(data) {
    this.dialogDisplay = true;
    this.idsArray = [];
    this.idsArray.push(data.did);
  }
  sureDelete() {
    this.equipmentService.deleteConfig(this.idsArray).subscribe(res => {
      // console.log(res);
      if (res === '00000') {
        this.msgPop = [];
        this.msgPop.push({severity: 'success', summary: '消息提示', detail: '删除成功'});
        this.refreshDataTable();
      }else {
        this.msgPop = [];
        this.msgPop.push({severity: 'error', summary: '提示消息', detail: '删除失败' + '\n' + res });
      }
      this.dialogDisplay = false;
    });
  }
  view(data) {
    // console.log(data);
    this.isDisable = true;
    this.title = '查看';
    this.addDisplay = true;
    this.dataName = data.label;
    this.val1 = data.status;
    this.addOrEdit = '';
    this.myForm.get('nodeName').disable({onlySelf: true, emitEvent: true});
  }

}
